package com.lavettacn.android.app.sociallessness.view;

import com.lavettacn.android.app.sociallessness.util.Debug;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WebViewDialog extends Dialog {

    private static final String TAG = "WebViewDialog";
    private static final float[] DIMENSIONS_DIFF_LANDSCAPE = {20, 60};
    private static final float[] DIMENSIONS_DIFF_PORTRAIT = {40, 60};
    private static final int MARGIN = 4;
    private static final int PADDING = 2;
    private static final FrameLayout.LayoutParams FILL =
            new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                             ViewGroup.LayoutParams.FILL_PARENT);

    private ProgressDialog mSpinner;
    private WebView mWebView;
    private String mUrl;
    private LinearLayout mContent;
    private TextView mTitleView;
    private String mTitle;
    private WebViewDialogListener mListener;

    public WebViewDialog(Context context, String title, String url,
            WebViewDialogListener listener) {
        super(context);
        mUrl = url;
        mTitle = title;
        mListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpinner = new ProgressDialog(getContext());
        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");
        mSpinner.setOnCancelListener(new SpinnerCancelListener());

        mContent = new LinearLayout(getContext());
        mContent.setOrientation(LinearLayout.VERTICAL);
        setUpTitle();
        setUpWebView();
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        final float scale =
            getContext().getResources().getDisplayMetrics().density;
        int orientation =
            getContext().getResources().getConfiguration().orientation;
        float[] dimensions =
            (orientation == Configuration.ORIENTATION_LANDSCAPE)
                    ? DIMENSIONS_DIFF_LANDSCAPE : DIMENSIONS_DIFF_PORTRAIT;
        addContentView(mContent, new LinearLayout.LayoutParams(
                display.getWidth() - ((int) (dimensions[0] * scale + 0.5f)),
                display.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
        setOnCancelListener(new DialogCancellListener());
    }

    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mTitleView = new TextView(getContext());
        mTitleView.setText(mTitle);
        mTitleView.setTextColor(Color.WHITE);
        mTitleView.setTypeface(Typeface.DEFAULT_BOLD);
        mTitleView.setBackgroundColor(Color.BLUE);
        mTitleView.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitleView.setCompoundDrawablePadding(MARGIN + PADDING);
        mContent.addView(mTitleView);
    }

    private void setUpWebView() {
        mWebView = new WebView(getContext());
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new WebViewDialogClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);
        mContent.addView(mWebView);
    }

    private class WebViewDialogClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean ret = mListener.shouldOverrideUrlLoading(view, url);
            if (ret) {
                WebViewDialog.this.dismiss();
            }
            Debug.logD(TAG, ": shouldOverrideUrlLoading, url=", url, ";ret=" + ret);
            return ret;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            Debug.logD(TAG, ": onReceivedError, failingUrl=", failingUrl);
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onReceivedError(view, errorCode, description, failingUrl);
            WebViewDialog.this.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Debug.logD(TAG, ": onPageStarted, url=", url);
            if (mListener.onPageStarted(view, url, favicon)) {
                view.stopLoading();
                WebViewDialog.this.dismiss();
                return;
            }
            super.onPageStarted(view, url, favicon);
            mSpinner.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Debug.logD(TAG, ": onPageFinished, url=", url);
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitleView.setText(title);
            }
            mSpinner.dismiss();
        }

    }

    private class SpinnerCancelListener implements OnCancelListener {

        public void onCancel(DialogInterface dialog) {
            mWebView.stopLoading();
            mListener.onCancel();
            WebViewDialog.this.dismiss();
        }
    }

    private class DialogCancellListener implements OnCancelListener {

        public void onCancel(DialogInterface dialog) {
            mListener.onCancel();
        }
    }

}
